package com.itboye.pondteam.pondteam;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.itboye.pondteam.R;
import com.itboye.pondteam.app.MyApplication;
import com.itboye.pondteam.base.BaseActivity;
import com.itboye.pondteam.bean.DeviceListBean;
import com.itboye.pondteam.custom.ptr.BasePtr;
import com.itboye.pondteam.custom.swipemenulistview.SwipeMenu;
import com.itboye.pondteam.custom.swipemenulistview.SwipeMenuCreator;
import com.itboye.pondteam.custom.swipemenulistview.SwipeMenuItem;
import com.itboye.pondteam.custom.swipemenulistview.SwipeMenuListView;
import com.itboye.pondteam.db.DBManager;
import com.itboye.pondteam.logincontroller.LoginController;
import com.itboye.pondteam.logincontroller.UnLoginState;
import com.itboye.pondteam.presenter.UserPresenter;
import com.itboye.pondteam.utils.Const;
import com.itboye.pondteam.utils.SPUtils;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.itboye.pondteam.volley.ResultEntity;
import com.umeng.message.UTrack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

import static com.itboye.pondteam.utils.EmptyUtil.getSp;

/**
 * Created by Administrator on 2017/3/16.
 */

public class MyDeviceActivity extends BaseActivity implements Observer {
    Button btn_addnew;
    TextView txt_title;
    SwipeMenuListView listview_device_list;
    UserPresenter userPresenter;
    String uid;
    TextView no_device;
    private SimpleAdapter listItemsAdapter;
    private static MyDeviceActivity instance;
    ImageView img_back;
    MyApplication myApp;
    TextView txt_tips;
    TextView txt_exist;
    DBManager dbManager;
    DeviceListBean selectionDevice;
    public ArrayList<DeviceListBean> arrayList = new ArrayList<>();
    private ProgressDialog loadingDialog;

    PtrFrameLayout ptr;
    private String currentDid;
    private String currentType;

    public static MyDeviceActivity getInstance() {
        return instance;
    }

    public static void setInstance(MyDeviceActivity instance) {
        MyDeviceActivity.instance = instance;
    }
    @Override
    protected void onResume() {
        super.onResume();
        getMyDeviceList();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device);
        instance = this;
        BasePtr.setRefreshOnlyStyle(ptr);
        ptr.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                BasePtr.setRefreshText("刷新中");
                getMyDeviceList();
            }
        });
        dbManager = new DBManager(this);
        myApp = (MyApplication) getApplication();
        myApp.deviceListActivityUI = this;
        img_back.setVisibility(View.GONE);
        txt_exist.setText(getString(R.string.exist_login));
        txt_title.setText(getString(R.string.device_list));
        userPresenter = new UserPresenter(this);
        // 把图片生成的ID加入img标签中 <img src='123'>
        String htmlText = getString(R.string.click) + "<img src='" + R.drawable.add_small + "'>" + getString(R.string.tips_detail);
        txt_tips.setText(Html.fromHtml(htmlText, new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                int id = Integer.parseInt(source);
                Drawable drawable = ContextCompat.getDrawable(MyDeviceActivity.this, id);//getResoueces.getDrawable(id,null)已经过时
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight());
                return drawable;
            }
        }, null));
        showProgressDialog(getString(R.string.posting),true);
        initSwipListView();
    }
    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    private void initSwipListView() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // TODO Auto-generated method stub
                SwipeMenuItem deleteItem = new SwipeMenuItem(MyDeviceActivity.this);
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                deleteItem.setTitle("删除");
                deleteItem.setTitleColor(Color.WHITE);
//				// set item width
                deleteItem.setWidth(dp2px(90));
                deleteItem.setTitleSize(18);
//				// set a icon
//				deleteItem.setIcon(R.drawable.ic_delete);
//				deleteItem.setBackground(R.drawable.delete_list_item_bg);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

        listview_device_list.setMenuCreator(creator);
        listview_device_list.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {

                switch (index) {
                    case 0:
//					ShopCarBean model=new ShopCarBean();
//					model.setId(dataList.getList().get(position).getId());
//					carPresenter.delete(model);
//                        MAlert.alert("删除了");
                        // open
//					open(item);
                        //删除设备操作
                        selectionDevice = arrayList.get(position);
                        //删除设备操作
                        userPresenter.deleteDevice(listItems.get(position).get("ID") + "");
                        break;
                    case 1:
                        // delete
//					delete(item);
//					mAppList.remove(position);
//					mAdapter.notifyDataSetChanged();
                        break;
                }
            }
        });
    }

    public void getMyDeviceList() {
        if (getSp(Const.UID).equals("")) {
            MAlert.alert(getString(R.string.unlogin));
            return;
        }
        userPresenter.getMyDeviceList(getSp(Const.UID));
    }


    ArrayList<HashMap<String, Object>> listItems = new ArrayList<HashMap<String, Object>>();

    private void initList(final ArrayList<DeviceListBean> arrayList) {

        listItems = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < arrayList.size(); i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("ItemName", arrayList.get(i).getDevice_nickname());
            map.put("ItemDid", "ID:" + arrayList.get(i).getDid());
            map.put("ItemState1", "");
            map.put("ItemState2", "");
            map.put("ID", arrayList.get(i).getId());
            map.put("psw", "sunsun123456");
            map.put("type", arrayList.get(i).getDevice_type());
            map.put("ItemRightArrow", R.drawable.ic_right_arrow);
            listItems.add(map);
        }
        listItemsAdapter = new SimpleAdapter(this, listItems,
                R.layout.device_item, new String[]{"ItemName", "ItemDid",
                "ItemState1", "ItemState2", "ItemRightArrow"},
                new int[]{R.id.textView_dev_name, R.id.textView_dev_did,
                        R.id.textView_dev_state1, R.id.textView_dev_state2,
                        R.id.imageView_dev_right_arrow});
        listview_device_list.setAdapter(listItemsAdapter);
        listview_device_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectionDevice = MyDeviceActivity.this.arrayList.get(position);
                loadingDialog = new ProgressDialog(MyDeviceActivity.this);
                loadingDialog.setTitle(getString(R.string.tips));
                loadingDialog.setMessage(getString(R.string.get_deviceInfoing));
                loadingDialog.setCanceledOnTouchOutside(false);
                loadingDialog.show();
                currentDid = listItems.get(position).get("ItemDid").toString().substring(3, listItems.get(position).get("ItemDid").toString().length());
                currentType = listItems.get(position).get("type").toString();
                userPresenter.getDeviceDetailInfo(currentDid, getSp((Const.UID)), "");
            }
        });
        listview_device_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//                AlertDialog.Builder alert = new AlertDialog.Builder(MyDeviceActivity.this);
//                alert.setTitle(getString(R.string.tips));
//                alert.setMessage(getString(R.string.make_sure_delete));
//                alert.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        selectionDevice = arrayList.get(position);
//                        //删除设备操作
//                        userPresenter.deleteDevice(listItems.get(position).get("ID") + "");
//                    }
//                });
//                alert.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });
//                alert.create();
//                alert.show();
                selectionDevice = arrayList.get(position);
                myApp.mEditDeviceInfo = selectionDevice;
                Intent mainIntent = new Intent(MyDeviceActivity.this,
                        EditDeviceActivity.class);
                mainIntent.putExtra("id",selectionDevice.getId());
                MyDeviceActivity.this.startActivity(mainIntent);
                return true;
            }
        });
        if (arrayList == null) {
            no_device.setVisibility(View.VISIBLE);
            return;
        }
        if (arrayList.size() <= 0) {
            no_device.setVisibility(View.VISIBLE);
        } else {
            no_device.setVisibility(View.GONE);
        }
    }

    private void startDeviceUI(final boolean b) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadingDialog.dismiss();
                Intent intent = new Intent(MyDeviceActivity.this, ActivityPondDeviceDetail.class);
                try {
                    intent.putExtra("did", selectionDevice.getDid());
                    intent.putExtra("device", selectionDevice.getDevice_nickname());
                    intent.putExtra("ID", selectionDevice.getId());
//                    intent.putExtra("psw", listItems.get(position).get("psw") + ""
                    intent.putExtra("hasPsw", b);
                    startActivity(intent);
                } catch (Exception e) {
                    MAlert.alert("device DID has error");
                }
            }
        }, 2000);
    }

    public void deleteOrUpdateDevice(String id, String nickName, boolean isDelete) {
        //详情页面做了删除操作
        Iterator<HashMap<String, Object>> iterator = listItems.iterator();
        int position = 0;
        while (iterator.hasNext()) {

            HashMap<String, Object> ar = iterator.next();
            if (ar.get("ID").equals(id)) {
                if (isDelete) {
                    //做了删除操作
                    iterator.remove();
                    //
                    arrayList.remove(position);
                } else {
                    //做了修改名称的操作
                    ar.put("ItemName", nickName);
                    arrayList.get(position).setDevice_nickname(nickName);
                }
                break;
            }
            position++;
        }
        listItemsAdapter.notifyDataSetChanged();
        if (listItems.size() <= 0) {
            no_device.setVisibility(View.VISIBLE);
        } else {

            no_device.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.txt_exist:
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.setTitle(getString(R.string.alert));
                alert.setMessage(getString(R.string.make_sure_exit));
                alert.setNegativeButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteUserInfo();
                    }
                });
                alert.setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                alert.create();
                alert.show();
                break;
            case R.id.btn_addnew:
//                showPopwindow(0);
                Intent intent = new Intent(this, AddPondDevice.class);
                startActivity(intent);
                break;
        }
    }

    private void showPopwindow(final int position) {
        View popView = View.inflate(this, R.layout.add_menu_windss, null);

        TextView open_configuration = (TextView) popView
                .findViewById(R.id.open_configuration);
        TextView open_camera = (TextView) popView
                .findViewById(R.id.open_camera);
        TextView pick_image = (TextView) popView.findViewById(R.id.pick_image);
        TextView camera_cancel_tv = (TextView) popView
                .findViewById(R.id.camera_cancel_tv);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels - 20;

        final PopupWindow popWindow = new PopupWindow(popView, width, ActionBar.LayoutParams.WRAP_CONTENT);
        // popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失


        open_configuration.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                popWindow.dismiss();
                Intent mainIntent  = new Intent(MyDeviceActivity.this,
                        AddPondDevice.class);
//                } else {
                mainIntent.putExtra("device_type", "pondTeam");
                mainIntent.putExtra("position", position);
//                }
                startActivity(mainIntent);
//						Intent mainIntent = new Intent(AddDeviceNewActivity.this,
//								MDeviceActivity.class);
//						startActivity(mainIntent);
            }
        });
        open_camera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // 添加局域网设备
                popWindow.dismiss();
                Intent mainIntent = new Intent(MyDeviceActivity.this,
                        LocalAreaDeviceActivity.class);
                startActivity(mainIntent);
            }
        });
        pick_image.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // 手动添加设备
                popWindow.dismiss();
                Intent mainIntent = new Intent(MyDeviceActivity.this,
                        ManualAddDeviceActivity.class);
                startActivity(mainIntent);
            }
        });
        camera_cancel_tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                popWindow.dismiss();
            }
        });

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(popView, Gravity.BOTTOM
                | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    private void deleteUserInfo() {
        myApp.getInstance().mPushAgent.removeAlias(getSp(Const.UID), "sunsun_filter_vat", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean b, String s) {
                System.out.println(b + "  222  " + s);
            }
        });
        SPUtils.put(this, null, Const.UID, "");
        SPUtils.put(this, null, Const.PaySecret, "");
        SPUtils.put(this, null, Const.USERNAME, "");
        SPUtils.put(this, null, Const.PASSWORD, "");
        SPUtils.put(this, null, Const.MOBILE, "");
        SPUtils.put(this, null, Const.IS_LOGINED, false);
        SPUtils.put(this, null, Const.HEAD, "");
        SPUtils.put(this, null, Const.NICK, "");
        SPUtils.put(this, null, Const.S_ID, "");

        LoginController.setLoginState(new UnLoginState());
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void update(Observable o, Object data) {
        ResultEntity resultEntity = handlerError(data);
        try {
            ptr.refreshComplete();
            closeProgressDialog();
        } catch (Exception e) {

        }
        if (resultEntity != null) {
            if (resultEntity.getCode() != 0) {
                try {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(loadingDialog!=null){
                                loadingDialog.dismiss();
                            }
                        }
                    }, 2000);
                } catch (Exception e) {

                }
                MAlert.alert(resultEntity.getMsg());
                return;
            }
            if (resultEntity.getEventType() == UserPresenter.getMyDeviceList_success) {
                arrayList = (ArrayList<DeviceListBean>) resultEntity.getData();
                initList(arrayList);
            } else if (resultEntity.getEventType() == UserPresenter.getMyDeviceList_fail) {
                MAlert.alert(resultEntity.getData());
            } else if (resultEntity.getEventType() == UserPresenter.deleteDevice_success) {
                MAlert.alert(resultEntity.getData());
                dbManager.deleteDeviceDataByDid(selectionDevice.getDid(),getSp(Const.UID));
                getMyDeviceList();
            } else if (resultEntity.getEventType() == UserPresenter.deleteDevice_fail) {
                MAlert.alert(resultEntity.getData());
            } else if (resultEntity.getEventType() == UserPresenter.authDevicePwdsuccess) {
                loadingDialog.setMessage(resultEntity.getData() + "");
                startDeviceUI(true);
            } else if (resultEntity.getEventType() == UserPresenter.authDevicePwdfail) {
                loadingDialog.setMessage(resultEntity.getData() + "");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.dismiss();
                    }
                }, 2000);
            } else if (resultEntity.getEventType() == UserPresenter.getdeviceinfosuccess) {
                loadingDialog.setMessage(getString(R.string.get_device_status_success) + getString(R.string.yanzhenging));
                String psw = dbManager.queryDevicePswByDid(currentDid,getSp(Const.UID));
                if (psw.equals("")) {
                    startDeviceUI(false);
                } else {
                    userPresenter.authDevicePwd(currentDid, psw, currentType);
                }
            } else if (resultEntity.getEventType() == UserPresenter.getdeviceinfofail) {
                MAlert.alert(resultEntity.getData());
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.dismiss();
                    }
                }, 2000);
            }
        }

    }
}
